import React, { useEffect } from "react";
import { useState } from "react";
import ReactMarkdown from "react-markdown";
import gfm from 'remark-gfm'
import rehypeRaw from "rehype-raw";
import { IAddCommentParam, IComment, IGoodSaveParam, ISingleArticle } from "../../interface/Article";
import { Add, Checked, Good, NoAvatar, Report, RightArrow, Saved, UnGood, UnSave } from "../../source/svgs";
import style from './style.less'
import { addComment, getArticles, getDetailArticle, setGood, setSave } from "../../service/article";
import LoginBox from "../LoginBox";
import { Form, message, Modal, Button, Checkbox, Image, Empty, Input } from "antd";
import { focusAuthor, getUserInfo } from "../../service/account";
import { originUserInfo, UserInfo } from "../../interface/account";
import cookieStore from "../../store/cookie";
import { myTip } from "../../tools/publicFun";
import TextArea from "antd/lib/input/TextArea";
import { IReportParams } from "../../interface/reports";
import { report } from "../../service/reports";
import { ITab } from "../../interface/tab";
import { useNavigate } from "react-router-dom";
import Pinglun from "../Pinglun";


export default function ArticleBox() {
  const [goodNum, setGoodNum] = useState<number>(0)
  const [saveNum, setSaveNum] = useState<number>(0)
  const [goodStat, setGoodStat] = useState<boolean>(false)
  const [saveStat, setSaveStat] = useState<boolean>(false)
  const [userInfo, setUserInfo] = useState<UserInfo>(originUserInfo)
  const [hasFocus, setHasFocus] = useState<boolean>(false)
  const [articleId, setArticleId] = useState<string>('')
  const [article, setArticle] = useState<ISingleArticle>()
  const [showLoginModal, setShowLoginModal] = useState<boolean>(false)
  const [showReportModal, setShowReportModal] = useState<boolean>(false)
  const [similarArticle, setSimilarArticle] = useState<ISingleArticle[]>([])
  const [isSelf, setIsSelf] = useState<boolean>(userInfo.id === article?.author.id)
  const [comment, setComment] = useState<string>('')
  const navigate = useNavigate()

  useEffect(() => {
    setArticleId(window.location.href.split("=")[1])
  }, [])

  useEffect(() => {
    handleGetArticleDetail({ articleId: articleId })
    // eslint-disable-next-line
  }, [articleId])

  useEffect(() => {
    if (article?.id !== '') {
      getSimilarArticle({ author: article?.author.id, tab: article?.tabs })
    }
    // eslint-disable-next-line
  }, [article])

  async function handleSetFocus() {
    // throw new Error("Function not implemented.");
    const user = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (user.stat === 'ok') {
      setUserInfo(user.data)
      if (user.data.id === article?.author.id!) {
        setIsSelf(true)
      } else {
        const data = await focusAuthor({ userId: user.data.id, targetId: article?.author?.id! })
        if (data.stat === 'ok') {
          setHasFocus(!hasFocus)
          myTip('已关注', 'success')
        } else {
          // myTip(data.msg, 'fail')
        }
      }

    } else {
      alert("检测到未登录，请登录")
      setShowLoginModal(true)
    }
  }

  async function getSimilarArticle(params: { author?: string, tab?: ITab[] }) {
    if (params.tab) {
      params.tab.forEach(async (element) => {
        const tabData = await getArticles({ tab: element.lable })
        if (tabData.stat === 'ok') {
          setSimilarArticle([...similarArticle, ...tabData.data.data.filter((item: ISingleArticle) => item.id !== article?.id)])
        }
      });
    }
    if (params.author) {
      const authorData = await getArticles({ authorId: params.author })
      if (authorData.stat === 'ok') {
        setSimilarArticle([...similarArticle, ...authorData.data.data.filter((item: ISingleArticle) => item.id !== article?.id)])
      }
    }
  }

  async function handleGetArticleDetail(params: { articleId: string }) {
    const data: { stat: string, data: ISingleArticle } = await getDetailArticle(params)
    if (data.stat === 'ok') {
      setArticle(data.data)
      setGoodNum(data.data.like.length)
      setSaveNum(data.data.save.length)
    }
    const user = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (user.stat === 'ok') {
      setUserInfo(user.data)
      setIsSelf(data.data?.author.id === user.data.id)
      if (data.data?.like.filter((item: string) => item === user.data.id).length === 1) {
        setGoodStat(true)
      }
      if (data.data?.save.filter((item: string) => item === user.data.id).length === 1) {
        setSaveStat(true)
      }
    }
  }

  async function handleSetGood(params: IGoodSaveParam) {
    const user = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (user.stat === 'ok') {
      setUserInfo(user.data)
      const data = await setGood(params)
      if (data.stat === 'ok') {
        setGoodStat(!goodStat)
        if (goodStat) {
          setGoodNum(goodNum - 1)
        } else {
          setGoodNum(goodNum + 1)
        }
        // window.location.reload()
      } else {
        message.warn("参数错误")
      }
    } else {
      alert("检测到未登录，请登录")
      setShowLoginModal(true)
    }
  }

  async function handleSetSave(params: IGoodSaveParam) {
    const user = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (user.stat === 'ok') {
      setUserInfo(user.data)
      const data = await setSave(params)
      if (data.stat === 'ok') {
        setSaveStat(!saveStat)
        if (saveStat) {
          setSaveNum(saveNum - 1)
        } else {
          setSaveNum(saveNum + 1)
        }
        // window.location.reload()
      } else {
        myTip("参数错误", 'warning')
      }
    } else {
      alert("检测到未登录，请登录")
      setShowLoginModal(true)
    }
  }

  async function handleReport(params: { content: string, type: string[] }) {
    // throw new Error("Function not implemented.");
    const requestParams: IReportParams = { ...params, targetType: 'article', articleId: article?.id!, userId: userInfo.id }
    const user = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (user.stat === 'ok') {
      setUserInfo(user.data)
      const data = await report(requestParams)
      if (data.stat === 'ok') {
        myTip("举报成功", 'success')
        setShowReportModal(false)
      } else {
        myTip(data.msg, 'fail')
      }
    } else {
      alert("检测到未登录，请登录")
      setShowLoginModal(true)
    }
  }

  function handleJumpToUserPage(id: string) {
    // throw new Error("Function not implemented.");
    navigate("/userInfo/userId=" + id)

  }

  async function handleAddComment() {
    // throw new Error("Function not implemented.");
    const requestParams: IAddCommentParam = { content: comment, authorId: userInfo.id, articleId: article?.id! }
    const user = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (user.stat === 'ok') {
      setUserInfo(user.data)
      const data = await addComment(requestParams)
      if (data.stat === 'ok') {
        myTip("评论成功", 'success')
        setComment('')
        handleGetArticleDetail({ articleId: articleId })
      } else {
        message.error(data.msg)
      }
    } else {
      alert("检测到未登录，请登录")
      setShowLoginModal(true)
    }
  }

  async function reFreshUserAfterLogin() {
    setShowLoginModal(false)
    const user = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (user.stat === "ok") {
      // publishHandle()
      setUserInfo(user.data)
    } else {
      alert("请先登录")
      setShowLoginModal(true)
    }
  }

  return (
    <React.Fragment>
      <div>
        <div className={style.content}>
          <div className={style.articleInfoPart}>
            <div>
              <div className={style.baseUserInfo}>
                <Image width={60} height={60} className={style.avatar} src={article?.author?.avatar! || NoAvatar} alt="" />
                <div className={style.nameFocus}>
                  {isSelf ? (<div></div>) : (<div style={{ "backgroundColor": hasFocus ? "#eaeaea" : "rgb(58, 240, 131)" }} onClick={() => handleSetFocus()} className={style.addFocus}><img src={hasFocus ? Checked : Add} alt="" /><span>{hasFocus ? "已" : ""}关注</span></div>)}
                  <div className={style.nickName}><span>{article?.author?.nickname!}</span></div>
                </div>
              </div>
              <div onClick={() => { handleJumpToUserPage(article?.author?.id!) }} className={style.turnToUserPage}><span className={style.turnToTxt}>去他的主页看看</span><img className={style.rightArrow} src={RightArrow} alt="" /></div>
              <div className={style.detailInfo}>
                <div className={style.aboutRecommend}>
                  <div className={style.aboutRecommendTitle}>{"相关推荐"}</div>
                  {Array.from(new Set(similarArticle)).length === 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={false} /> : similarArticle.map((article: ISingleArticle, index: number) => (
                    <div className={style.singleRecommend} onClick={() => { navigate("/article/id=" + article.id); window.location.reload() }} key={article.id + index}>
                      <div><span>{article.title}</span></div>
                      <div><span>{article.content.slice(0, 30)}...</span></div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
          <div className={style.articleContent}>
            <div></div>
            <div>
              <div className={style.contentTop}>
                <div className={style.articleTitle}>
                  <span>{article?.title}</span>
                </div>
                <div className={style.goodSave}>
                  <div onClick={() => { handleSetGood({ type: 'article', articleId: article!.id, userId: userInfo.id }) }} className={style.optionBlock}>
                    <img className={style.goodSaveIcon} src={goodStat ? Good : UnGood} alt="good" /><span className={style.number}>{goodNum}</span>
                  </div>
                  <div onClick={() => { handleSetSave({ type: 'article', articleId: article!.id, userId: userInfo.id }) }} className={style.optionBlock}>
                    <img className={style.goodSaveIcon} src={saveStat ? Saved : UnSave} alt="save" /><span className={style.number}>{saveNum}</span>
                  </div>
                  <div onClick={() => { setShowReportModal(true) }} className={style.optionBlock}>
                    <img className={style.goodSaveIcon} src={Report} alt="report" />
                  </div>
                </div>
              </div>
              <div className={style.articleContentBox}>
                <ReactMarkdown remarkPlugins={[gfm]} rehypePlugins={[rehypeRaw]} children={article?.content!} className={style.userInfoPart} />
              </div>
              <div className={style.commentBar}>
                <Input value={comment} onChange={(value) => { setComment(value.target.value) }} className={style.addComment} placeholder={"我也来说两句："} />
                <span onClick={() => { handleAddComment() }} className={style.commentBtn}>发送</span></div>
              <div className={style.commentsBox}>
                {article?.comments.length === 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={false} /> : (
                  article?.comments.map((comment: IComment, index: number) => (
                    <div key={comment.id + index}>
                      <Pinglun funGood={(params: IGoodSaveParam) => handleSetGood(params)} funFresh={() => { handleGetArticleDetail({ articleId: article.id }) }} userInfo={userInfo} articleId={article.id} comment={comment} />
                    </div>
                  ))
                )}
              </div>
            </div>
          </div>
        </div>
        <Modal zIndex={1} destroyOnClose onCancel={() => { setShowLoginModal(false) }} footer={null} className={style.interrap} visible={showLoginModal}>
          <LoginBox afterLogin={() => { reFreshUserAfterLogin() }} />
        </Modal>
        <Modal zIndex={2} destroyOnClose onCancel={() => { setShowReportModal(false) }} footer={null} visible={showReportModal}>
          <Form className={style.reportForm} onFinish={(value: { content: string, type: string[] }) => { handleReport(value) }}>
            <Form.Item label={"请填写举报原因"} name={"content"}>
              <TextArea maxLength={200} />
            </Form.Item>
            <Form.Item label={"请选择其中一到三项"} name={"type"}>
              <Checkbox.Group >
                <Checkbox value={"1"}>含有色情内容</Checkbox>
                <Checkbox value={"2"}>涉及第三方资金相关内容</Checkbox>
                <Checkbox value={"3"}>含有不良政治言论</Checkbox>
                <Checkbox value={"4"}>其他违规内容</Checkbox>
              </Checkbox.Group>
            </Form.Item>
            <Form.Item>
              <Button htmlType={"submit"} type={"primary"}>举报</Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </React.Fragment >
  )
}